package demo.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import demo.pojo.response.Result;
import demo.utils.JWTUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

@Slf4j
@Component
public class AutoFilter implements GlobalFilter, Ordered {

    //    使用nacos的配置中心
//    List<String> write = List.of("blog-user-info/login", "blog-user-info/register");
    @Autowired
    WriteName write;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        Assert.notNull(write, "write must not be null");

        String uri = request.getURI().toString();

        log.info("global uri:{}", uri);

        for (String write : write.getUrl()) {
            if (uri.contains(write)) {
//                传递到下一个过滤器
                return chain.filter(exchange);
            }
        }

        //不是白名单 检查token
        List<String> token = request.getHeaders().get("user_token");

        token = token == null ? List.of(request.getCookies().get("user_token").get(0).toString()) : token;

        Assert.notNull(token, "token must not be null");

        log.info("token:{}", token);
        try {
            if (JWTUtils.parseJWT(token.get(0)) == null) {
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("拒绝请求");
            return unauthorizedResponse(exchange, "jwt令牌校验失败");
        }

        return chain.filter(exchange);
    }

    //    拒绝请求
    @SneakyThrows
    public Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String
            msg) {
        log.error("[⽤⼾⾝份认证异常]请求路径: {}", exchange.getRequest().getPath());
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON_VALUE);
        Result result = Result.fail(msg);
        DataBuffer dataBuffer =
                response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));
    }

    //设置过滤器执行的顺序 值越小执行优先级越高越先执行
    @Override
    public int getOrder() {
        return -250;
    }
}

